package top.kaoshanji.q1ch03a.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import top.kaoshanji.q1ch03a.domain.User;
import top.kaoshanji.q1ch03a.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 代码清单-q1ch03a-65页a：LoginController
 * @author kaoshanji
 * ^_^
 * create time 2025/5/3 19:34
 */
@Controller
public class LoginController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/index.html", method = RequestMethod.GET)
    public String loginPage() {
        return "login";
    }

    @RequestMapping(value = "/loginCheck.html", method = RequestMethod.POST)
    public ModelAndView loginCheck(HttpServletRequest request, LoginCommand loginCommand) {
        boolean isValidUser = userService.hasMatchUser(loginCommand.getUserName(), loginCommand.getPassword());

        if (!isValidUser) {
            return new ModelAndView("login", "error", "用户名或密码错误。");
        } else {
            User user = userService.findUserByUserName(loginCommand.getUserName());

            user.setLastIp(request.getLocalAddr());
            user.setLastVisit(new Date());

            request.getSession().setAttribute("user", user);

            userService.loginSuccess(user);

            return new ModelAndView("main");
        }

    }


}
